﻿using System;
using System.Linq;
using System.Web.Mvc;
using MSDAL;
using PagedList;
using MSWEB.Implementation;
using MSDAL.Implementation;
using MSWeb.Implementation;
using log4net;
using System.Collections.Generic;

namespace MSWeb.Controllers
{
    public class WyplataController : Controller
    {
        readonly ILog _loger = LogManager.GetLogger(typeof(WyplataController));
        private readonly MSEntities _db;
        private readonly LessonRepository _lessonRepo;
        private readonly DataRepository _dataRepo;
        private const int pageSize = 10;

        public WyplataController()
        {
            _db = new MSEntities();
            _dataRepo = new DataRepository();
            _lessonRepo = new LessonRepository();
        }

        public ActionResult WyplataZaLekcje()
        {
            ViewBag.IDLekcji = _lessonRepo.GetOpenedLessonsForTeacher();
            return PartialView("_TworzenieWyplat");
        }

        [Authorize]
        public ActionResult WidokWyplat(int? page, string searchString, string currentFilter, string sortOrder)
        {
            ViewBag.CurrentSort = sortOrder;
            ViewBag.SurnameNameSortParm = String.IsNullOrEmpty(sortOrder) ? "surname_desc" : "";
            ViewBag.DateSortParm = sortOrder == "Date" ? "date_desc" : "Date";
            if (searchString != null)
            {
                page = 1;
            }
            else
            {
                searchString = currentFilter;
            }
            ViewBag.CurrentFilter = searchString;
            int pageNumber = (page ?? 1);

            var payments = from w in _db.Wyplaty
                           select w;

            if (!String.IsNullOrEmpty(searchString))
            {
                payments = _db.Wyplaty
                    .Where(s => s.Lekcje.FirstOrDefault().Nauczyciele.Nazwisko.Contains(searchString));
            }
            switch (sortOrder)
            {
                case "surname_desc":
                    payments = payments.OrderByDescending(i => i.Lekcje.FirstOrDefault().Nauczyciele.Nazwisko);
                    break;
                case "Date":
                    payments = payments.OrderBy(i => i.Data);
                    break;
                case "date_desc":
                    payments = payments.OrderByDescending(i => i.Data);
                    break;
                default:
                    payments = payments.OrderBy(i => i.WyplataId);
                    break;
            }

            return View(payments
                    .ToPagedList(pageNumber, pageSize));
        }

        [Authorize]
        public ActionResult DodawanieWyplat()
        {
            var result = new WyplataZaLekcjeDodaj
            {
                Nauczyciel = _dataRepo.GetNauczyciele().ToList(),
                Lekcje = new List<SelectListItem>()
            };
            return View("DodawanieWyplat", result);
        }

        [Authorize]
        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult GetLessonForTeacher(int teacherId)
        {
            try
            {
                var result = _dataRepo.GetLessonBasedOnTeacherId(teacherId);
                return Json(result.ToList(), JsonRequestBehavior.AllowGet);
            }
            catch
            {
                TempData["Error"] = "Wystapił błąd ładowania danych.";
                return RedirectToAction("WidokWyplat");
            }
        }

        [Authorize]
        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult GetPriceForTeacher(string value)
        {
            try
            {
                if (value == "null")
                {
                    return Json(0, JsonRequestBehavior.AllowGet);
                }
                else
                {
                    string[] values = value.Split(',');
                    var lessons = values.Select(item => int.Parse(item)).ToList();
                    var result = _lessonRepo.GetSumTeacherPayment(lessons);
                    return Json(result, JsonRequestBehavior.AllowGet);
                }

            }
            catch
            {
                TempData["Error"] = "Wystapił błąd ładowania danych.";
                return RedirectToAction("WidokWyplat");
            }
        }
        [Authorize]
        public ActionResult GetLessonForPayment(int id)
        {
            var result = new List<Lekcje>();
            result = _db
                .Lekcje
                .Where(i => i.WyplataId == id)
                .ToList();
            return PartialView("_LinkedLessonToPaymentPerStudent", result);            
        }

        [HttpPost]
        [Authorize]
        [ValidateAntiForgeryToken]
        public ActionResult Create(WyplataZaLekcjeDodaj wyplata)
        {
            try
            {
                if (!_dataRepo.SavePaymentForTeacher(wyplata))
                {
                    TempData["Error"] = "Wystapił błąd podczas dodawania wpisu.";
                    return RedirectToAction("WidokWyplat");
                }
            }
            catch (Exception ex)
            {
                _loger.Error("Error! User: " + User.Identity.Name, ex);
                TempData["Error"] = "Wystapił błąd podczas dodawania wpisu.";
                return RedirectToAction("WidokWyplat");
            }
            return RedirectToAction("WidokWyplat");
        }
    }
}